package com.richman.view;

import javax.swing.JPanel;
import javax.swing.JPopupMenu;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

import com.richman.ps38.entity.Event;
import com.richman.ps38.entity.HGEvent;

public class HGPS38TeamMatchPane extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1111111111L;
	private JTextField textField;
	
	
	
	
	//new 
	
	private String hgCurrentLeague = "";
	private String hgCurrentTeam = "";
	
	private String ps38CurrentLeague  = "";
	private String ps38CurrentTeam = "";
	
	private int currentStat = 0; //0是在联赛界面， 1是在球队界面
	
	private Vector<String> hasMergedAllLeague = new Vector<String>();
	
	
	private Vector<String[]> alreadyMergeLeague = new Vector<String[]>();
	
	
	private  Vector<String[]> alreadyMergeTeams = new Vector<String[]>();
	
	
	
	
	private Vector<HGEvent> localHGevents = new Vector<HGEvent>();
	
	private  ReadWriteLock locklocalHGevents = new ReentrantReadWriteLock();
	
	private Vector<Event> localPS38events = new Vector<Event>(); 
	
	private  ReadWriteLock locklocalPS38events = new ReentrantReadWriteLock();
	
	
	
	private String hgDelTeam = "";
	private String ps38DelTeam = "";
	
	private String hgDelLeague = "";
	
	//new end
	
	
	
	private String searchText = "";
	
	
	
	
	
	
	
	private Vector<String[]> alreadyMergeTeamsShowItems = new Vector<String[]>();
	
	
	
	private Vector<String[]> HGTeams = new Vector<String[]>();
	
	private Vector<String[]> PS38Teams = new Vector<String[]>();
	
	
	

	
    
    //hg tables
    HGTeamsTableModel hgteamstablemodel = new HGTeamsTableModel();
    JTable hgteamstable = null;
    private JPopupMenu m_hgtablepopupMenu;
    private String[] hgSelectedItem = null;
    private String[] hgChooseItem = null;
    
    JMenuItem hgchooseMenuItem = null;
    JMenuItem hgmergeMenuItem = null;
    
    
    
    //ps38 tables
    PS38TeamsTableModel ps38teamstablemodel = new PS38TeamsTableModel();
    JTable ps38teamstable = null;
    private JPopupMenu m_ps38tablepopupMenu;
    private String[] ps38SelectedItem = null;
    private String[] ps38ChooseItem = null;
    
    JMenuItem ps38chooseMenuItem = null;
    JMenuItem ps38mergeMenuItem = null;
    
    
    JLabel lblSb = null;
    
    
    

	/**
	 * Create the panel.
	 */
	public HGPS38TeamMatchPane() {
		setLayout(null);
		
//		JLabel label = new JLabel("已合并球队：");
//		label.setBounds(22, 35, 99, 21);
//		add(label);
		
		
		
		
	    DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        tcr.setHorizontalAlignment(JLabel.CENTER);
		
		
		

		
//		JLabel label_1 = new JLabel("搜索：");
//		label_1.setBounds(22, 66, 54, 15);
//		add(label_1);
		
//		textField = new JTextField();
//		textField.setBounds(84, 66, 99, 21);
//		add(textField);
//		textField.setColumns(10);
		
		
		
//		textField.addKeyListener(new KeyListener(){
//            public void keyPressed(KeyEvent e) {  
//                if (e.getKeyCode() == KeyEvent.VK_ENTER) {  
//                	searchText = textField.getText();  
//                    
//               
//                    
//                }  
//                // System.out.println("Text " + value);  
//            }  
//            public void keyReleased(KeyEvent e) {  
//            }  
//            public void keyTyped(KeyEvent e) {  
//            }  
//
//        });
		
		
		
		
		
		
		
		
		JLabel label_2 = new JLabel("待合并：");
		label_2.setBounds(20, 8, 121, 15);
		add(label_2);
		
		lblSb = new JLabel("SB：");
		lblSb.setBounds(20, 36, 300, 15);
		add(lblSb);
		
		
		
		
		
		
		
		
		//hg teams table
		
		hgteamstable = new JTable(hgteamstablemodel);

		hgteamstable.setRowHeight(30);
		hgteamstable.setFont(new java.awt.Font("微软雅黑", Font.PLAIN, 13));

		hgteamstable.setDefaultRenderer(Object.class, tcr);
		

		
		
		m_hgtablepopupMenu = new JPopupMenu();
		hgchooseMenuItem = new JMenuItem();
		hgchooseMenuItem.setText("解除匹配");
		hgchooseMenuItem.addActionListener(new java.awt.event.ActionListener() {  
            public void actionPerformed(java.awt.event.ActionEvent evt) {  
                //该操作需要做的事  
            	
            	System.out.println("1即将要删除的联赛："+ hgDelLeague);
            	
            	try{
            		
            		 boolean delSuc = false;
	          	       for(int i = 0; i < alreadyMergeLeague.size(); i++) {
	           			
	           			if(alreadyMergeLeague.elementAt(i)[0].equals(hgDelLeague)) {
	           				
	           				alreadyMergeLeague.removeElementAt(i);
	           				updateLeagueMatch();
	           				updateHGTeamsTable();
	           				updatePS38TeamsTable();
	           				delSuc = true;
	           				System.out.println("2即将要删除的联赛："+ hgDelLeague);

	           				break;
	           			}
	           			
	           			
	           			
	           		}
	          	       
	          	     hgDelLeague = "";
        	       
	          	    if(delSuc == true) {
	         			JOptionPane.showMessageDialog(null, "已解除匹配", "已解除匹配", JOptionPane.DEFAULT_OPTION);
	         		}
            		
            		
            	}catch(Exception e){
            		e.printStackTrace();
            	}

            }  
        });
		

		
		m_hgtablepopupMenu.add(hgchooseMenuItem);
		
		
		
		
		hgteamstable.addMouseListener(new java.awt.event.MouseAdapter() {  
            public void mouseClicked(java.awt.event.MouseEvent evt) {  
     	       //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键  
     	       if (evt.getButton() == java.awt.event.MouseEvent.BUTTON1) {  
     	          
     	    	 
     	    	   
     	           //弹出菜单  
     	         int selectedRow = hgteamstable.rowAtPoint(evt.getPoint());
     	           
     	         if(selectedRow == -1) {
     	        	 return;
     	         }
     	         
     	         
     	         if(currentStat == 0) {
     	        	hgCurrentLeague = HGTeams.elementAt(selectedRow)[0];
         	        
         	        lblSb.setText("SB 联赛:" + hgCurrentLeague);
     	         }else if(currentStat == 1) {
     	        	
     	        	hgCurrentTeam = HGTeams.elementAt(selectedRow)[0];
     	        	 
     	        	
     	        	lblSb.setText("SB 联赛:" + hgCurrentLeague + "  球队" + hgCurrentTeam);
     	         }
     	         
     	        
     	         
     	        
     	        
     	        
     	        
     	        
     	       }else if(evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
     	    	   
     	    	   if(currentStat == 1) {
     	    		  currentStat = 0;
     	    		  updateHGTeamsTable();
     	    		 updatePS38TeamsTable();
     	    	   }else if(currentStat == 0) {
     	    		 int selectedRow = hgteamstable.rowAtPoint(evt.getPoint());        	           
          	         if(selectedRow == -1) {
          	        	 return;
          	         }
          	         hgDelLeague = HGTeams.elementAt(selectedRow)[0];
          	         System.out.println("即将要删除的联赛："+ hgDelLeague);
          	       m_hgtablepopupMenu.show(hgteamstable, evt.getX(), evt.getY());  
          	       
     	    	   }
     	    	   
     	       }
            }  
        });
		
		
		hgteamstable.getTableHeader().addMouseListener(new MouseAdapter()  //表头添加事件
				  {
            public void mouseClicked(java.awt.event.MouseEvent evt) {  
      	       //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键  
      	       if(evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
      	    	   
      	    	   if(currentStat == 1) {
      	    		  currentStat = 0;
      	    		  updateHGTeamsTable();
      	    		 updatePS38TeamsTable();
      	    	   }
      	    	   
      	       }
             } 
				  });
		
		JScrollPane scrollPane_1 = new JScrollPane(hgteamstable);
		scrollPane_1.setBounds(30, 67, 564, 426);
		add(scrollPane_1);
		
		JLabel lblPs = new JLabel("PS38：");
		lblPs.setBounds(599, 6, 54, 15);
		add(lblPs);
		
		
		
		
		
		
		//ps38 teams
		
		ps38teamstable = new JTable(ps38teamstablemodel);
		
		
		ps38teamstable.setRowHeight(30);
		ps38teamstable.setFont(new java.awt.Font("微软雅黑", Font.PLAIN, 13));

		
		ps38teamstable.setDefaultRenderer(Object.class, tcr);
		
		
		
		
		m_ps38tablepopupMenu = new JPopupMenu();
		ps38chooseMenuItem = new JMenuItem();
		ps38chooseMenuItem.setText("解除匹配");
		ps38chooseMenuItem.addActionListener(new java.awt.event.ActionListener() {  
            public void actionPerformed(java.awt.event.ActionEvent evt) {  
                //该操作需要做的事  
            	
            	try{
            		
            		boolean delSuc = false;
            		
            		
            		if(currentStat == 0) {
            			for(int i = 0; i < alreadyMergeLeague.size(); i++) {
                			
                			if(alreadyMergeLeague.elementAt(i)[0].equals(hgDelTeam) && alreadyMergeLeague.elementAt(i)[1].equals(ps38DelTeam)) {
                				
                				alreadyMergeLeague.removeElementAt(i);
                				updateLeagueMatch();
                				updateHGTeamsTable();
                				updatePS38TeamsTable();
                				delSuc = true;
                				
                			
                				
                				break;
                			}
                			
                		}
                		
                		hgDelTeam = "";
                		ps38DelTeam = "";
            		}else if(currentStat == 1) {
            			for(int i = 0; i < alreadyMergeTeams.size(); i++) {
                			
                			if(alreadyMergeTeams.elementAt(i)[0].equals(hgDelTeam) && alreadyMergeTeams.elementAt(i)[1].equals(ps38DelTeam)) {
                				
                				alreadyMergeTeams.removeElementAt(i);
                				updateHGPS38TeamsList();
                				updateHGTeamsTable();
                				updatePS38TeamsTable();
                				delSuc = true;
                				
                			
                				
                				break;
                			}
                			
                		}
                		
                		hgDelTeam = "";
                		ps38DelTeam = "";
            		}
            		
            		
            		
            		if(delSuc == true) {
            			JOptionPane.showMessageDialog(null, "已解除匹配", "已解除匹配", JOptionPane.DEFAULT_OPTION);
            		}
            		
            		
            	}catch(Exception e){
            		e.printStackTrace();
            	}

            }  
        });
		

		
		m_ps38tablepopupMenu.add(ps38chooseMenuItem);
		
		
		
		
		
		ps38teamstable.addMouseListener(new java.awt.event.MouseAdapter() {  
            public void mouseClicked(java.awt.event.MouseEvent evt) {  
     	       //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键  
     	       if (evt.getButton() == java.awt.event.MouseEvent.BUTTON1) {  
     	          
     	         //弹出菜单  
     	         
     	         
     	         
     	        if(evt.getClickCount() == 2){

     	        	int selectedRow = ps38teamstable.rowAtPoint(evt.getPoint());
     	        	
     	        	
     	        	 if(selectedRow == -1 ) {
         	        	 return;
         	         }
         	         
     	        	 
     	        	 
     	        	
     	        	 
     	        	 if(currentStat == 0) {//联赛合并
     	        		 
     	        		 
     	        		ps38CurrentLeague = PS38Teams.elementAt(selectedRow)[0];
     	        		 
     	        		
     	        		if(!PS38Teams.elementAt(selectedRow)[0].equals("") && !PS38Teams.elementAt(selectedRow)[1].equals("")) {
     	        			
     	        			hgCurrentLeague = PS38Teams.elementAt(selectedRow)[1];
     	        			
     	        			lblSb.setText("SB 联赛:" + hgCurrentLeague);
     	        			
     	        			ps38CurrentLeague = PS38Teams.elementAt(selectedRow)[0];
     	        			
     	        		}
     	        		
     	        		
     	        		 boolean leagueAlreadyMerge = false;
     	        		 
     	        		 
     	        		 /*if(hgCurrentLeague.equals("")) {
     	        			hgCurrentLeague = PS38Teams.elementAt(selectedRow)[1];
     	        			
     	        			lblSb.setText("SB 联赛:" + hgCurrentLeague);
     	        			
     	        		 }
     	        		 
     	        		 if(hgCurrentLeague.equals("")) {
     	        			 return;
     	        		 }*/
     	        		 
     	        		 
     	        		 
     	        		 for(int i = 0; i < alreadyMergeLeague.size(); i++) {
     	        			 
     	        			 if(alreadyMergeLeague.elementAt(i)[0].equals(hgCurrentLeague) || alreadyMergeLeague.elementAt(i)[1].equals(ps38CurrentLeague)) {
     	        				 
     	        				 
     	        				 
     	        				 if( !(alreadyMergeLeague.elementAt(i)[0].equals(hgCurrentLeague) && alreadyMergeLeague.elementAt(i)[1].equals(ps38CurrentLeague)) ) {
     	        					/*alreadyMergeLeague.removeElementAt(i);
    	        					 
     	        					String[] mergeLeagueItem = {hgCurrentLeague, ps38CurrentLeague}; 
     	     	        			 
     	     	        			alreadyMergeLeague.add(mergeLeagueItem);*/
     	        					 
     	        					JOptionPane.showMessageDialog(null, "请先解除原联赛匹配", "错误", JOptionPane.ERROR_MESSAGE);
     	        					
     	        					return;
     	        					 
     	     	        			
/*     	     	        			updateLeagueMatch();
     	     	        			updatePS38TeamsTable();*/
     	        				 }
     	        				 
     	        				 
     	        				leagueAlreadyMerge = true;
     	        				 
     	        				currentStat = 1;
     	        				 
     	        				hgCurrentTeam = "";
     	        				
     	        				 break;
     	        				 
     	        			 }
     	        			 
     	        		 }
     	        		 
     	        		 
     	        		 if(leagueAlreadyMerge == false) {//新的联赛匹配
     	        			 
     	        			String[] mergeLeagueItem = {hgCurrentLeague, ps38CurrentLeague}; 
     	        			 
     	        			alreadyMergeLeague.add(mergeLeagueItem);
     	        			
     	        			//updateLeagueMatch();
     	        			
     	        			currentStat = 1;
     	        			 
     	        			hgCurrentTeam = "";
     	        			 
     	        		 }
     	        		 
     	        		updateLeagueMatch();
     	        		updateHGTeamsTable();
        				updatePS38TeamsTable();
     	        		 
     	        		 
     	        		 
     	        		 
     	        	 }else if(currentStat == 1) {
     	        		 
     	        		ps38CurrentTeam = PS38Teams.elementAt(selectedRow)[0];
     	        		
     	        		if(hgCurrentTeam.equals("")) {
     	        			return;
     	        		}
     	        		 
     	        		boolean teamAlreadyMerge = false;
     	        		
     	        		 for(int i = 0; i < alreadyMergeTeams.size(); i++) {
     	        			 
     	        			 if(alreadyMergeTeams.elementAt(i)[0].equals(hgCurrentTeam) || alreadyMergeTeams.elementAt(i)[1].equals(ps38CurrentTeam)) {
     	        				 
     	        				 if(!(alreadyMergeTeams.elementAt(i)[0].equals(hgCurrentTeam) && alreadyMergeTeams.elementAt(i)[1].equals(ps38CurrentTeam))) {
     	        					 //do nothing
     	        					alreadyMergeTeams.removeElementAt(i);
     	        					
     	        					String[] mergeTeamItem = {hgCurrentTeam, ps38CurrentTeam};
     	        					alreadyMergeTeams.add(mergeTeamItem);
     	        					
     	        					updateHGPS38TeamsList();
     	        					
     	        					updatePS38TeamsTable();
     	        					 
     	        				 }
     	        				 
     	        				teamAlreadyMerge = true;
     	        				 
     	        				 break;
     	        				 
     	        			 }
     	        			 
     	        		 }
     	        		 
     	        		 if(teamAlreadyMerge == false) {
     	        			 
     	        			String[] mergeTeamItem = {hgCurrentTeam, ps38CurrentTeam};
	        				alreadyMergeTeams.add(mergeTeamItem);
     	        			 
	        				updateHGPS38TeamsList();
	        				updatePS38TeamsTable();
     	        			 
     	        		 }
     	        		 
     	        		 
     	        	 }
     	        	 

     	        }
     	         
     	         
     	        
     	        
     	           
     	    	
     	       }// 双击事件 
     	       else if(evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {//右键事件
     	    	   
     	    	  int selectedRow = ps38teamstable.rowAtPoint(evt.getPoint()); 
     	    	  
     	    	  if(PS38Teams.elementAt(selectedRow)[0].equals("") || PS38Teams.elementAt(selectedRow)[1].equals("")) {
     	    		  return;
     	    	  }
     	    	  
     	    	  
     	    	  hgDelTeam = PS38Teams.elementAt(selectedRow)[1];
     	    	  ps38DelTeam = PS38Teams.elementAt(selectedRow)[0];
     	    	  
     	    	   
     	    	  m_ps38tablepopupMenu.show(ps38teamstable, evt.getX(), evt.getY());  
     	       }
            }  
        });
		
		
		
		
		
		
		
		
		JScrollPane scrollPane_2 = new JScrollPane(ps38teamstable);
		scrollPane_2.setBounds(605, 67, 583, 426);
		add(scrollPane_2);

		readHGPS38TeamsList();
		readLeagueMatch();
		
		
	}
	
	
	//already merge teams
	
	public void updateHGPS38TeamsList() {		
		try{	
			File file = new File("data/" + "HGPS38teamMatch.txt");

			if(!file.exists()){	
				file.createNewFile();
			}
			
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));

			String str = "";
			for(String [] obs : alreadyMergeTeams) {
				str = obs[0] + "," + obs[1];
				fwlocal.append(str);
				fwlocal.newLine();
				fwlocal.flush();
			}
			
			

			fwlocal.close();

			
			
			
	
		}catch(FileNotFoundException e) {
			e.printStackTrace();
			return;
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}
	}
	
	
	
	private boolean hasMergedAllLeagueFunc(String hgLeague, String ps38League) {
		
		boolean hasMergedAll = true;
		
		try {
			
			Vector<String> hgMergeTeams = new Vector<String>();
			Vector<String> ps38MergeTeams = new Vector<String>();
			
			for(int i = 0; i < alreadyMergeTeams.size(); i++) {
				
				hgMergeTeams.add(alreadyMergeTeams.elementAt(i)[0]);
				ps38MergeTeams.add(alreadyMergeTeams.elementAt(i)[1]);
				
			}
			
			for(int i = 0; i < localHGevents.size(); i++) {
				
				if(localHGevents.elementAt(i).leagueName.equals(hgLeague)) {
					
					if(!hgMergeTeams.contains(localHGevents.elementAt(i).homeTeam) || !hgMergeTeams.contains(localHGevents.elementAt(i).awayTeam)) {
						hasMergedAll = false;
					}

				}
				
			}
			
			if(hasMergedAll == false) {
				hasMergedAll = true;
				for(int i = 0; i < localPS38events.size(); i++) {
					
					if(localPS38events.elementAt(i).leagueName.equals(ps38League)) {
						
						if(!ps38MergeTeams.contains(localPS38events.elementAt(i).homeTeam) || !ps38MergeTeams.contains(localPS38events.elementAt(i).awayTeam)) {
							hasMergedAll = false;
						}

					}
					
				}
			}
			
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
		return hasMergedAll;
	}


	private void readHGPS38TeamsList() {
		File file = new File("data/" + "HGPS38teamMatch.txt");
		
		if(!file.exists()) {
			System.out.println("[teamMatch] 文件不存在");
			return;
		}
		
		BufferedReader freader = null;
		try {
			freader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			
			String str = "";
			while ((str = freader.readLine()) != null) {
				String[] contents = str.split(",");
				if(contents.length == 2){
					String [] mergeteam = new String[2];
					mergeteam[0] = contents[0];
					mergeteam[1] = contents[1];

					alreadyMergeTeams.add(mergeteam);
				}
			}
			
			freader.close();
			
			//updateShowItem();
			
			
			
		} catch(FileNotFoundException e) {
			e.printStackTrace();
			return;
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}
					
	}
	
	
	
	
	private void readLeagueMatch() {
		File file = new File("data/" + "HGPS38leagueMatch.txt");
		
		if(!file.exists()) {
			System.out.println("[leagueMatch] 文件不存在");
			return;
		}
		
		BufferedReader freader = null;
		try {
			freader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			
			String str = "";
			while ((str = freader.readLine()) != null) {
				String[] contents = str.split(",");
				if(contents.length == 2){
					String [] mergeLeague = new String[2];
					mergeLeague[0] = contents[0];
					mergeLeague[1] = contents[1];

					

					alreadyMergeLeague.add(mergeLeague);
	        
				}
			}
			
			freader.close();
			
			//updateShowItem();
			
			
			
		} catch(FileNotFoundException e) {
			e.printStackTrace();
			return;
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}
					
	}
	
	private void updateLeagueMatch() {
		
		try{	
			File file = new File("data/" + "HGPS38leagueMatch.txt");

			if(!file.exists()){	
				file.createNewFile();
			}
			
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));

			String str = "";
			for(String [] obs : alreadyMergeLeague) {
				str = obs[0] + "," + obs[1];
				fwlocal.append(str);
				fwlocal.newLine();
				fwlocal.flush();
			}
			
			

			fwlocal.close();

			
	
		}catch(FileNotFoundException e) {
			e.printStackTrace();
			return;
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}
		
	}
	
	
	
	
	
	
	



	public Vector<String[]> getHGPS38TeamsList(){
		return alreadyMergeTeams;
	}
	
	
	
	public Vector<String[]> getHGPS38LeaguesList(){
		return alreadyMergeLeague;
	}
	
	

    
    //hg teams
    
    public void updateHGTeams(Vector<HGEvent> hgevents) {
    	
    	
    	
    	if(hgevents == null) {
    		return;
    	}
    	
    	
    	
    	
    	locklocalHGevents.writeLock().lock();
    	
    	
    	if(localHGevents.size() != 0) {
    		localHGevents.clear();
    	}
    	
    	
    	for(int i = 0; i < hgevents.size(); i++) {

    		localHGevents.add(hgevents.elementAt(i));

    	}
    	
    	locklocalHGevents.writeLock().unlock();
    	
    	
    	updateHGTeamsTable();
    	
    	
    }
    
    
    public synchronized void updateHGTeamsTable() {
    	
    	try {
    		
    		locklocalHGevents.readLock().lock();
    		
    		HGTeams.clear();
    		
    		Vector<String> leagues = new Vector<String>();
    		
    		if(currentStat == 0) {
    			
	    		for(int i = 0; i < localHGevents.size(); i++) {
	    			
	    			if(leagues.contains(localHGevents.elementAt(i).leagueName)) {
	    				continue;
	    			}
	    			
    				String[] item = {localHGevents.elementAt(i).leagueName};	
    				
    				if(!leagues.contains(item[0])) {
    					HGTeams.add(item);
    					leagues.add(item[0]);
    				}
	
	        	}
    		
    		}else if(currentStat == 1) {
    			
    			for(int i = 0; i < localHGevents.size(); i++) {
	    			
    				if(localHGevents.elementAt(i).leagueName.equals(hgCurrentLeague)) {
        				String[] item = {localHGevents.elementAt(i).homeTeam};
        				
        				boolean alreadyIn = false;
        				
        				for(int ii = 0; ii < HGTeams.size(); ii++) {    
        					
        					if(HGTeams.elementAt(ii)[0].equals(item[0])) {
        						alreadyIn = true;
        						break;
        					}
        					
        							
        				}
        				
        				
        				if(alreadyIn == false) {
        					HGTeams.add(item);        			
        				}
        				
        				
        				alreadyIn = false;
        				
        				String[] item1 = {localHGevents.elementAt(i).awayTeam};
        				
        				for(int ii = 0; ii < HGTeams.size(); ii++) {    
        					
        					if(HGTeams.elementAt(ii)[0].equals(item1[0])) {
        						alreadyIn = true;
        						break;
        					}
        					
        							
        				}
        				
        				
        				if(alreadyIn == false) {
        					HGTeams.add(item1);        			
        				}
        				
        				
    				}

    			}
    			
    		}
    		
    		
    		setOneRowBackgroundColor();
    		
    		hgteamstablemodel.updateTable();
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	locklocalHGevents.readLock().unlock();
    	
    }
	
    
    
    
    public class HGTeamsTableModel extends AbstractTableModel  
    {  
        /**
		 * 
		 */
		private static final long serialVersionUID = 100861L;
		/* 
         * 这里和刚才一样，定义列名和每个数据的值 
         */  
        String[] columnNames =  
        { "皇冠"};
        

  
        /** 
         * 构造方法，初始化二维数组data对应的数据 
         */  
        public HGTeamsTableModel()  
        {  

        }  
  
        // 以下为继承自AbstractTableModle的方法，可以自定义  
        /** 
         * 得到列名 
         */  
        @Override  
        public String getColumnName(int column)  
        {  
            return columnNames[column];  
        }  
          
        /** 
         * 重写方法，得到表格列数 
         */  
        @Override  
        public int getColumnCount()  
        {  
            return columnNames.length;  
        }  
  
        /** 
         * 得到表格行数 
         */  
        @Override  
        public int getRowCount()  
        {         
	        if(null == HGTeams){
	    		return 0;
	    	}
            return HGTeams.size();  
        }  
  
        /** 
         * 得到数据所对应对象 
         */  
        @Override  
        public Object getValueAt(int rowIndex, int columnIndex)  
        {  
            //return data[rowIndex][columnIndex];
        	return HGTeams.elementAt(rowIndex)[columnIndex];
        }  
  
        /** 
         * 得到指定列的数据类型 
         */  
        @Override  
        public Class<?> getColumnClass(int columnIndex)  
        {  
        	
        	return String.class;
        	

        	
        }  
  
        /** 
         * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑 
         */  
        @Override  
        public boolean isCellEditable(int rowIndex, int columnIndex)  
        {  
            return false;
        }  
          
        /** 
         * 如果数据单元为可编辑，则将编辑后的值替换原来的值 
         */  
        @Override  
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)  
        {  
            HGTeams.elementAt(rowIndex)[columnIndex] = (String)aValue;  
            /*通知监听器数据单元数据已经改变*/  
            fireTableCellUpdated(rowIndex, columnIndex);  
        }  
        
        public void updateTable(){
        	fireTableDataChanged();
        }
        
  
    }  
    
    

    //ps38 teams
    
    public void updatePS38Teams(Vector<Event> ps38Events) {
    	
    	if(ps38Events == null) {
    		return;
    	}
    	
    	
    	locklocalPS38events.writeLock().lock();
    	
    	if(localPS38events.size() != 0) {
    		localPS38events.clear();
    	}
    	
    	for(int i = 0; i < ps38Events.size(); i++) {

    		localPS38events.add(ps38Events.elementAt(i));

    	}
    	
    	locklocalPS38events.writeLock().unlock();
    	
    	
    	updatePS38TeamsTable();
    	
    }
    
    
    public synchronized void updatePS38TeamsTable() {
    	
    	try {
    		
    		
    		locklocalPS38events.readLock().lock();
    		
        	PS38Teams.clear();
        	
        	
        	if(currentStat == 0) {//联赛界面

        		Vector<String> leagues = new Vector<String>();
        		
        		Vector<String> hgLeagues = new Vector<String>();
				for(int k = 0; k < localHGevents.size(); k++) {
					hgLeagues.add(localHGevents.elementAt(k).leagueName);
					
				}
        		
            	
            	for(int i = 0; i < localPS38events.size(); i++) {
            		
            		
            		boolean mergealready = false;
            		
            		
            		if(leagues.contains(localPS38events.elementAt(i).leagueName)) {
            			continue;
            		}
            		
            		
            		
            		for(int j = 0; j < alreadyMergeLeague.size(); j++) {
            			
            			if(alreadyMergeLeague.elementAt(j)[1].equals(localPS38events.elementAt(i).leagueName)) {
            				String[] ps38event = {localPS38events.elementAt(i).leagueName, alreadyMergeLeague.elementAt(j)[0]};
            				mergealready  = true;        	
            				
            				if(hgLeagues.contains(alreadyMergeLeague.elementAt(j)[0])) {
            					PS38Teams.add(ps38event);
            				}
            				
            				
            				        				
            				break;
            			}
            			
            		}
            		
            		if(mergealready == false) {
            			String[] ps38event = {localPS38events.elementAt(i).leagueName, ""};
            			
            			PS38Teams.add(ps38event);
            		}
            		
            		
            		leagues.add(localPS38events.elementAt(i).leagueName);

            		
            	}
        		
        	}else if(currentStat == 1) {//球队界面
        		
            	for(int i = 0; i < localPS38events.size(); i++) {
            		

            		if(localPS38events.elementAt(i).leagueName.equals(ps38CurrentLeague)) {
            			
                		String[] ps38event = {localPS38events.elementAt(i).homeTeam, ""};
                		
                		for(int j = 0; j < alreadyMergeTeams.size(); j++) {
                			
                			if(alreadyMergeTeams.elementAt(j)[1].equals(localPS38events.elementAt(i).homeTeam)) {
                				ps38event[1] =  alreadyMergeTeams.elementAt(j)[0];
     				
                				break;
                			}
                			
                			
                			
                		}
                		
                		boolean alreadyIn = false;
                		
                		for(int ii = 0; ii < PS38Teams.size(); ii++) {
                			if(PS38Teams.elementAt(ii)[0].equals(ps38event[0])) {
                				alreadyIn = true;
                				break;
                			}
                		}
                		
                		if(alreadyIn == false) {
                			PS38Teams.add(ps38event);
                		}
                		
                		
                		
                		String[] ps38event1 = {localPS38events.elementAt(i).awayTeam, ""};
                		
                		
                		for(int j = 0; j < alreadyMergeTeams.size(); j++) {
                			if(alreadyMergeTeams.elementAt(j)[1].equals(localPS38events.elementAt(i).awayTeam)) {
                				ps38event1[1] =  alreadyMergeTeams.elementAt(j)[0];
     				
                				break;
                			}
                			
                		}
                		
                		
                		boolean alreadyIn1 = false;
                		
                		for(int ii = 0; ii < PS38Teams.size(); ii++) {
                			if(PS38Teams.elementAt(ii)[0].equals(ps38event1[0])) {
                				alreadyIn1 = true;
                				break;
                			}
                		}
                		
                		if(alreadyIn1 == false) {
                			PS38Teams.add(ps38event1);
                		}

            			
            		}
            		
            		

            		
            	}
        		
        	}
        	
        	setPS38RowBackgroundColor();

        	ps38teamstablemodel.updateTable();
    		
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	locklocalPS38events.readLock().unlock();
    	
    }
	
    
    
    
    public class PS38TeamsTableModel extends AbstractTableModel  
    {  
        /**
		 * 
		 */
		private static final long serialVersionUID = 100861L;
		/* 
         * 这里和刚才一样，定义列名和每个数据的值 
         */  
        String[] columnNames =  
        { "PS38", "皇冠"};
        

  
        /** 
         * 构造方法，初始化二维数组data对应的数据 
         */  
        public PS38TeamsTableModel()  
        {  

        }  
  
        // 以下为继承自AbstractTableModle的方法，可以自定义  
        /** 
         * 得到列名 
         */  
        @Override  
        public String getColumnName(int column)  
        {  
            return columnNames[column];  
        }  
          
        /** 
         * 重写方法，得到表格列数 
         */  
        @Override  
        public int getColumnCount()  
        {  
            return columnNames.length;  
        }  
  
        /** 
         * 得到表格行数 
         */  
        @Override  
        public int getRowCount()  
        {         
	        if(null == PS38Teams){
	    		return 0;
	    	}
            return PS38Teams.size();  
        }  
  
        /** 
         * 得到数据所对应对象 
         */  
        @Override  
        public Object getValueAt(int rowIndex, int columnIndex)  
        {  
            //return data[rowIndex][columnIndex];
        	return PS38Teams.elementAt(rowIndex)[columnIndex];
        }  
  
        /** 
         * 得到指定列的数据类型 
         */  
        @Override  
        public Class<?> getColumnClass(int columnIndex)  
        {  
        	
        	return String.class;
        	

        	
        }  
  
        /** 
         * 指定设置数据单元是否可编辑.这里设置"姓名","学号"不可编辑 
         */  
        @Override  
        public boolean isCellEditable(int rowIndex, int columnIndex)  
        {  
            return false;
        }  
          
        /** 
         * 如果数据单元为可编辑，则将编辑后的值替换原来的值 
         */  
        @Override  
        public void setValueAt(Object aValue, int rowIndex, int columnIndex)  
        {  
        	PS38Teams.elementAt(rowIndex)[columnIndex] = (String)aValue;  
            /*通知监听器数据单元数据已经改变*/  
            fireTableCellUpdated(rowIndex, columnIndex);  
        }  
        
        public void updateTable(){
        	fireTableDataChanged();
        }
        
  
    }  
    
    
    
    

    
    
    //
    
    public void setOneRowBackgroundColor() {
    	

    	
        try {  
        	
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
            	
            	
  
                public Component getTableCellRendererComponent(JTable table,  
                        Object value, boolean isSelected, boolean hasFocus,  
                        int row, int column) {  


                	
                	if(currentStat == 0) {
                		
                		
                			String hgitem = HGTeams.elementAt(row)[0];
                			
                			boolean merge = false;
                			
                			for(int j = 0; j < alreadyMergeLeague.size(); j++) {
                				if(alreadyMergeLeague.elementAt(j)[0].equals(hgitem)) {
                					
                					merge = true;
                					break;
                				}
                			}
                			
                			if(merge == true) {
                				setBackground(new Color(222,222,243));
                			}else {
                				setBackground(new Color(246,246,246));  
                			}
                			
                		
                		
                	}else if(currentStat == 1) {
                		
            			String hgitem = HGTeams.elementAt(row)[0];
            			
            			boolean merge = false;
            			
            			for(int j = 0; j < alreadyMergeTeams.size(); j++) {
            				if(alreadyMergeTeams.elementAt(j)[0].equals(hgitem)) {
            					
            					merge = true;
            					break;
            				}
            			}
            			
            			if(merge == true) {
            				setBackground(new Color(222,222,243));
            			}else {
            				setBackground(new Color(246,246,246));  
            			}
                		
                	}
                	
                    
                    setHorizontalAlignment(JLabel.CENTER);
  
                    return super.getTableCellRendererComponent(table, value,  
                            isSelected, hasFocus, row, column);  
                }  
            };  
            int columnCount = hgteamstable.getColumnCount();  
            for (int i = 0; i < columnCount; i++) {  
            	hgteamstable.getColumn(hgteamstable.getColumnName(i)).setCellRenderer(tcr);
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    
    }  

    
    
    public void setPS38RowBackgroundColor() {
    	

    	
        try {  
        	
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {
            	
            	
  
                public Component getTableCellRendererComponent(JTable table,  
                        Object value, boolean isSelected, boolean hasFocus,  
                        int row, int column) {  


                	
                	if(currentStat == 0) {
                		
                		
                		if(!PS38Teams.elementAt(row)[1].equals("")) {
                			
                			String hgLeague = PS38Teams.elementAt(row)[1];
                			String ps38League = PS38Teams.elementAt(row)[0];
                			
                			if(hasMergedAllLeagueFunc(hgLeague, ps38League)) {
                				setBackground(new Color(222,243,222));
                			}else {
                				setBackground(new Color(246,246,246));  
                			}
                		}else {
                			setBackground(new Color(246,246,246));  
                		}
                		
                			
                		
                	}
                	
                    
                    setHorizontalAlignment(JLabel.CENTER);
  
                    return super.getTableCellRendererComponent(table, value,  
                            isSelected, hasFocus, row, column);  
                }  
            };  
            int columnCount = ps38teamstable.getColumnCount();  
            for (int i = 0; i < columnCount; i++) {  
            	ps38teamstable.getColumn(ps38teamstable.getColumnName(i)).setCellRenderer(tcr);
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    
    }  
    
    
	
}
